package com.zipon.tpf.common;

/**
 * Created by zipon on 2018/9/6.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

public class HttpClientUtil {
    Logger log = new LogUtil("http_log").logger;
    /**
     * Post方式 得到JSONObject
     *
     * @param params post参数
     * @param url
     * @encoding 编码格式，这里直接写死为utf-8
     * @return
     */
    public JSONObject doPost(JSONObject params, String url, String encoding ) throws IOException {
        //创建httpClient连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;

        JSONObject resultJsonObject = new JSONObject();
        try {
            StringEntity entity = new StringEntity(params.toString(),"utf-8");
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type","application/json");
            // 为HttpPost设置实体数据
            httpPost.setEntity(entity);
            log.info("******************请求开始********************");
            log.info(String.format("请求url信息:%s",httpPost.getRequestLine()));
            log.info("请求headers信息：");
            String headerList ="";
            for (Header header :httpPost.getAllHeaders()){
                headerList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info(headerList);
            log.info("请求body:");
            log.info(httpEntityToJSONObject(httpPost.getEntity()));
            // HttpClient 发送Post请求
            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // CloseableHttpResponse
                HttpEntity httpEntity = httpResponse.getEntity();
                resultJsonObject = httpEntityToJSONObject(httpEntity);
            }else{
                resultJsonObject.put("errorMessage",httpResponse);
            }
            log.info("返回headers信息:");
            log.info(httpResponse.getAllHeaders());
            log.info("返回body:");
            log.info(httpResponse.getEntity());
            log.info("******************请求结束********************");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            httpResponse.close();
            httpClient.close();
        }
        return resultJsonObject;
    }

    /**
     * 没有headers 没有cookie插入的快速post
     * @param params
     * @param url
     * @return
     * @throws IOException
     */
    public BaseResponse doPost(JSONObject params, String url) throws IOException {
        //创建httpClient连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;

        BaseResponse baseResponse = new BaseResponse();
        try {
            StringEntity entity = new StringEntity(params.toString(),"utf-8");
            HttpPost httpPost = new HttpPost(url);
            // 为HttpPost设置实体数据
            httpPost.setEntity(entity);
//            默认Content-Type
            httpPost.addHeader("Content-Type","application/json");
            System.out.println(httpEntityToJSONObject(httpPost.getEntity()));
            // HttpClient 发送Post请求
            httpResponse = httpClient.execute(httpPost);
            baseResponse = httpResponseToBaseResponse(httpResponse);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            httpResponse.close();
            httpClient.close();
        }
        return baseResponse;
    }

    /**
     * 主用这个
     * @param params
     * @param url
     * @param headers
     * @param cookie
     * @return
     * @throws IOException
     */
    public BaseResponse doPost(JSONObject params, String url ,JSONObject headers ,String cookie) throws IOException {
        //创建httpClient连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;

        BaseResponse baseResponse = new BaseResponse();
        try {
            StringEntity entity = new StringEntity(params.toString(),"utf-8");
            HttpPost httpPost = new HttpPost(url);
            addHeaders(httpPost,headers);
            addCookies(httpPost,cookie);
            log.info("******************请求开始********************");
            log.info(String.format("请求url信息:%s",httpPost.getRequestLine()));
            String headerList ="";
            for (Header header :httpPost.getAllHeaders()){
                headerList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("请求headers信息：\r\n"+headerList.substring(0,headerList.length()-2));
            log.info("请求body:");
//            httpPost.addHeader("Content-Type","application/json");
            // 为HttpPost设置实体数据
            httpPost.setEntity(entity);
            log.info(httpEntityToJSONObject(httpPost.getEntity()));
            // HttpClient 发送Post请求
            httpResponse = httpClient.execute(httpPost);
            baseResponse = httpResponseToBaseResponse(httpResponse);
            String repheaderList ="";
            for (Header header :httpResponse.getAllHeaders()){
                repheaderList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("返回headers信息: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
            log.info("返回body:");
            log.info(httpResponseToBaseResponse(httpResponse).getResponseBody());
            log.info("******************请求结束********************");

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            httpResponse.close();
            httpClient.close();
        }
        return baseResponse;
    }

//
//    public JSONObject getJSONObjectByGet(String url) throws IOException {
//        JSONObject resultJsonObject=null;
//
//        //创建httpClient连接
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        // HttpClient 发送Post请求
//        CloseableHttpResponse httpResponse = null;
//        try{
//            StringBuilder urlStringBuilder=new StringBuilder(url);
//            //利用URL生成一个HttpGet请求
//            HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
////            httpGet.setHeader("Content-Type","text/123");
//            System.out.println(httpGet.getMethod());
//            for (Header header :httpGet.getAllHeaders()){
//                String key = header.getName();
//                String value = header.getValue();
//                System.out.println(String.format("%s:%s",key,value));
//            }
//            System.out.println(httpGet.getProtocolVersion());
//            System.out.println(httpGet.getRequestLine());
//
//            httpResponse=httpClient.execute(httpGet);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally{
//            httpResponse.close();
//            httpClient.close();
//        }
//        //得到httpResponse的状态响应码
//        if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {
//            //得到httpResponse的实体数据
//            HttpEntity httpEntity=httpResponse.getEntity();
//            resultJsonObject = httpEntityToJSONObject(httpEntity);
//        }
//        return resultJsonObject;
//    }

    /**
     * 不带headers、cookies参数的get请求
     * @param url
     * @return
     * @throws IOException
     */
    public BaseResponse getResponseByGet(String url) throws IOException  {
        //创建httpClient连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // HttpClient 发送get请求
        CloseableHttpResponse httpResponse = null;
        BaseResponse baseResponse = new BaseResponse();
        try{
            StringBuilder urlStringBuilder=new StringBuilder(url);
            //利用URL生成一个HttpGet请求
            HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
            log.info("******************请求开始********************");
            log.info(String.format("请求url信息:%s",httpGet.getRequestLine()));
            String headerList ="";
            for (Header header :httpGet.getAllHeaders()){
                headerList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("请求headers信息：\r\n"+headerList.substring(0,headerList.length()-2));
            httpResponse=httpClient.execute(httpGet);
            baseResponse = httpResponseToBaseResponse(httpResponse);
            String repheaderList ="";
            for (Header header :httpResponse.getAllHeaders()){
                repheaderList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("返回headers信息: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
            log.info("返回body:");
            log.info(baseResponse.getResponseBody());
            log.info("******************请求结束********************");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            httpResponse.close();
            httpClient.close();
        }
        return baseResponse;
    }

    public BaseResponse getResponseByGet(String url,JSONObject headers,String cookies) throws IOException {
        //创建httpClient连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // HttpClient 发送get请求
        CloseableHttpResponse httpResponse = null;
        BaseResponse baseResponse = new BaseResponse();
        try{
            StringBuilder urlStringBuilder=new StringBuilder(url);
            //利用URL生成一个HttpGet请求
            HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
            addHeaders(httpGet,headers);
            addCookies(httpGet,cookies);
            log.info("******************请求开始********************");
            log.info(String.format("请求url信息:%s",httpGet.getRequestLine()));
            String headerList ="";
            for (Header header :httpGet.getAllHeaders()){
                headerList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("请求headers信息：\r\n"+headerList.substring(0,headerList.length()-2));
            httpResponse=httpClient.execute(httpGet);
            baseResponse = httpResponseToBaseResponse(httpResponse);
            String repheaderList ="";
            for (Header header :httpResponse.getAllHeaders()){
                repheaderList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("返回headers信息: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
            log.info("返回body:");
            log.info(baseResponse.getResponseBody());
            log.info("******************请求结束********************");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            httpResponse.close();
            httpClient.close();
        }
        return baseResponse;
    }
    /**
     * 将HttpEntity类转换为JSONObject封装方法
     * @param httpEntity
     * @return
     */
    public JSONObject httpEntityToJSONObject(HttpEntity httpEntity){
        StringBuilder entityStringBuilder=new StringBuilder();
        JSONObject resultJsonObject=new JSONObject();

        if (httpEntity!=null) {
            BufferedReader reader=null;
            try {
                reader=new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
                String line=null;
                while ((line=reader.readLine())!=null) {
                    entityStringBuilder.append(line);
                }
                // 从HttpEntity中得到的json String数据转为json
                String json=entityStringBuilder.toString();
                resultJsonObject= JSON.parseObject(json);
            } catch (Exception e) {
//                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        //关闭流
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return resultJsonObject;
    }

    /**
     * 将httpResponse对象转换为自定义的BaseResponse对象
     * @param httpResponse
     * @return
     */
    public BaseResponse httpResponseToBaseResponse(CloseableHttpResponse httpResponse){
        //        遍历取出headers
        JSONArray headList = new JSONArray();
        for (Header header :httpResponse.getAllHeaders()){
            String key = header.getName();
            String value = header.getValue();
            JSONObject tempJson = new JSONObject();
            tempJson.put(key,value);
            headList.add(tempJson);
        }
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setHeaders(headList);
        baseResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        baseResponse.setResponseBody(httpEntityToJSONObject(httpResponse.getEntity()));

        return baseResponse;
    }

    /**
     * 为httpGet和httpPost加headers
     * @param httpEntityEnclosingRequestBase,HttpGet和HttpPost都是继承这个类
     * @param headers
     * @return
     */
    public HttpEntityEnclosingRequestBase addHeaders(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase, JSONObject headers){
        //循环加header
        if(headers!=null) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                httpEntityEnclosingRequestBase.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        return httpEntityEnclosingRequestBase;
    }
    /**
     * 为httpGet加headers
     * @param httpRequestBase,HttpGet和HttpPost都是继承这个类
     * @param headers
     * @return
     */
    public HttpRequestBase addHeaders(HttpRequestBase httpRequestBase, JSONObject headers){
        //循环加header
        if(headers!=null) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                httpRequestBase.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        return httpRequestBase;
    }

    /**
     * 为httpPost加cookies
     * @param httpEntityEnclosingRequestBase,HttpPost是继承这个类
     * @param cookies
     * @return
     */
    public HttpEntityEnclosingRequestBase addCookies(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase,String cookies){
        //循环加cookies
        if(cookies!=null) {
            httpEntityEnclosingRequestBase.addHeader("Cookie", cookies);
        }
        return httpEntityEnclosingRequestBase;
    }
    /**
     * 为httpPost加cookies
     * @param httpRequestBase,HttpGet是继承这个类
     * @param cookies
     * @return
     */
    public HttpRequestBase addCookies(HttpRequestBase httpRequestBase, String cookies){
        //循环加cookies
        if(cookies!=null) {
            httpRequestBase.addHeader("Cookie", cookies);
        }
        return httpRequestBase;
    }

}
